<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request, { SERVER_BASE_URL } from "@/utils/request.js"

// 路由实例
const route = useRoute()
const router = useRouter()

// 用户ID
const userId = ref(null)
// 订单ID
const orderNo = ref(null)
// 订单详情
const orderDetail = ref({
  order: {},
  items: [],
  delivery: {},
  payment: {}
})
// 加载状态
const loading = ref(false)
// 支付信息
const paymentInfo = ref({
  orderId: null,
  paymentNo: '',
  paymentPlatform: 'ALIPAY'
})
// 操作按钮的加载状态
const actionLoading = ref({
  cancel: false,
  pay: false,
  complete: false
})

// 计算属性：订单状态中文名称
const orderStatusText = computed(() => {
  const statusMap = {
    'PENDING_PAYMENT': '待付款',
    'PAID': '已付款',
    'SHIPPED': '已发货',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  }
  return statusMap[orderDetail.value.order.status] || orderDetail.value.order.status
})

// 计算属性：订单状态类型（用于显示不同颜色）
const orderStatusType = computed(() => {
  const typeMap = {
    'PENDING_PAYMENT': 'warning',
    'PAID': 'success',
    'SHIPPED': 'primary',
    'COMPLETED': 'success',
    'CANCELLED': 'info'
  }
  return typeMap[orderDetail.value.order.status] || ''
})

// 计算属性：支付方式中文名称
const paymentTypeText = computed(() => {
  const typeMap = {
    'ONLINE': '在线支付',
    'CASH': '货到付款'
  }
  return typeMap[orderDetail.value.order.paymentType] || orderDetail.value.order.paymentType
})

// 计算属性：配送状态中文名称
const deliveryStatusText = computed(() => {
  const statusMap = {
    'PENDING': '待分配',
    'ASSIGNED': '已分配',
    'PICKED': '已取件',
    'DELIVERED': '已送达'
  }
  return statusMap[orderDetail.value.delivery.deliveryStatus] || orderDetail.value.delivery.deliveryStatus
})

// 检查登录状态
const checkLoginStatus = () => {
  const userInfo = JSON.parse(localStorage.getItem('user'))
  if (!userInfo) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return false
  }
  
  userId.value = userInfo.id
  return true
}

// 获取订单详情
const getOrderDetail = async () => {
  if (!checkLoginStatus()) return
  
  loading.value = true
  try {
    const res = await request.get(`/order/detail/${orderNo.value}`);

    // console.log(res.data);
    
    if (res.code === 200) {
      orderDetail.value = res.data
      
      // 初始化支付信息
      paymentInfo.value.orderId = orderNo.value
      
      // 检查订单是否属于当前用户
      if (orderDetail.value.order.userId !== userId.value) {
        ElMessage.error('您无权查看该订单')
        router.push('/personal/orders')
        return
      }
    } else {
      ElMessage.error(res.message || '获取订单详情失败')
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  } finally {
    loading.value = false
  }
}

// 取消订单
const cancelOrder = async () => {
  if (!checkLoginStatus()) return
  
  try {
    await ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    actionLoading.value.cancel = true
    console.log(`/order/cancel/${orderNo.value}`)
    const res = await request.put(`/order/cancel/${orderNo.value}`)
    
    if (res.code === 200) {
      ElMessage.success('订单取消成功')
      getOrderDetail() // 刷新订单详情
    } else {
      ElMessage.error(res.message || '取消订单失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  } finally {
    actionLoading.value.cancel = false
  }
}

// 支付订单
const payOrder = async () => {
  if (!checkLoginStatus()) return
  
  // 验证支付信息
  if (!paymentInfo.value.paymentNo || paymentInfo.value.paymentNo.trim() === '') {
    ElMessage.warning('请输入支付流水号')
    return
  }
  
  try {
    actionLoading.value.pay = true
    console.log(paymentInfo.value)
    const res = await request.put('/order/pay', paymentInfo.value)
    
    if (res.code === 200) {
      ElMessage.success('订单支付成功')
      getOrderDetail() // 刷新订单详情
    } else {
      ElMessage.error(res.message || '支付订单失败')
    }
  } catch (error) {
    console.error('支付订单失败:', error)
    ElMessage.error('支付订单失败')
  } finally {
    actionLoading.value.pay = false
  }
}

// 确认收货
const completeOrder = async () => {
  if (!checkLoginStatus()) return
  
  try {
    await ElMessageBox.confirm('确认已收到商品吗？', '提示', {
      confirmButtonText: '确认收货',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    actionLoading.value.complete = true
    const res = await request.put(`/order/complete/${orderNo.value}`)
    
    if (res.code === 200) {
      ElMessage.success('确认收货成功')
      getOrderDetail() // 刷新订单详情
    } else {
      ElMessage.error(res.message || '确认收货失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认收货失败:', error)
      ElMessage.error('确认收货失败')
    }
  } finally {
    actionLoading.value.complete = false
  }
}

// 返回订单列表
const backToOrderList = () => {
  router.push('/personal/orders')
}

// 处理图片URL
const getImgUrl = (url) => {
  if (!url) return '';

  // 确保有服务器地址前缀
  let fullUrl = url;
  if (url.startsWith('/uploads/')) {
    fullUrl = SERVER_BASE_URL + url;
  }

  return fullUrl;
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
}

// 页面加载时获取订单ID并获取订单详情
onMounted(() => {
  if (!checkLoginStatus()) return

  orderNo.value = route.params.id
  if (!orderNo.value) {
    ElMessage.error('订单号不能为空')
    router.push('/personal/orders')
    return
  }
  
  getOrderDetail()
})
</script>

<template>
  <div class="order-detail-container">
    <el-card class="order-detail-card" v-loading="loading">
      <div class="page-header">
        <div class="header-left">
          <h2>订单详情</h2>
          <el-tag :type="orderStatusType">{{ orderStatusText }}</el-tag>
        </div>
        <div class="header-right">
          <el-button @click="backToOrderList">返回订单列表</el-button>
        </div>
      </div>
      
      <!-- 订单基本信息 -->
      <div class="section">
        <div class="section-title">订单信息</div>
        <div class="info-grid">
          <div class="info-item">
            <span class="label">订单编号：</span>
            <span>{{ orderDetail.order.orderNo || '-' }}</span>
          </div>
          <div class="info-item">
            <span class="label">创建时间：</span>
            <span>{{ formatDate(orderDetail.order.createTime) }}</span>
          </div>
          <div class="info-item">
            <span class="label">支付方式：</span>
            <span>{{ paymentTypeText }}</span>
          </div>
          <div class="info-item">
            <span class="label">订单备注：</span>
            <span>{{ orderDetail.order.remark || '无' }}</span>
          </div>
        </div>
      </div>
      
      <!-- 订单状态时间线 -->
      <div class="section">
        <div class="section-title">订单状态</div>
        <el-timeline>
          <el-timeline-item
            v-if="orderDetail.order.createTime"
            timestamp="订单创建"
            placement="top"
            color="#409EFF"
          >
            {{ formatDate(orderDetail.order.createTime) }}
          </el-timeline-item>
          
          <el-timeline-item
            v-if="orderDetail.order.paymentTime"
            timestamp="订单支付"
            placement="top"
            color="#67C23A"
          >
            {{ formatDate(orderDetail.order.paymentTime) }}
          </el-timeline-item>
          
          <el-timeline-item
            v-if="orderDetail.order.shippingTime"
            timestamp="订单发货"
            placement="top"
            color="#409EFF"
          >
            {{ formatDate(orderDetail.order.shippingTime) }}
          </el-timeline-item>
          
          <el-timeline-item
            v-if="orderDetail.order.completionTime"
            timestamp="订单完成"
            placement="top"
            color="#67C23A"
          >
            {{ formatDate(orderDetail.order.completionTime) }}
          </el-timeline-item>
          
          <el-timeline-item
            v-if="orderDetail.order.cancellationTime"
            timestamp="订单取消"
            placement="top"
            color="#909399"
          >
            {{ formatDate(orderDetail.order.cancellationTime) }}
          </el-timeline-item>
        </el-timeline>
      </div>
      
      <!-- 收货信息 -->
      <div class="section">
        <div class="section-title">收货信息</div>
        <div class="address-info" v-if="orderDetail.order.addressInfo">
          <div class="receiver-info">
            <span class="name">{{ orderDetail.order.addressInfo.receiverName }}</span>
            <span class="phone">{{ orderDetail.order.addressInfo.receiverPhone }}</span>
          </div>
          <div class="address">{{ orderDetail.order.addressInfo.detailedAddress }}</div>
        </div>
        <div v-else>暂无收货信息</div>
      </div>
      
      <!-- 商品信息 -->
      <div class="section">
        <div class="section-title">商品信息</div>
        <el-table :data="orderDetail.items" style="width: 100%">
          <el-table-column label="商品信息" min-width="400">
            <template #default="{ row }">
              <div class="commodity-info">
                <el-image
                  :src="row.image && row.image.length > 0 ? getImgUrl(row.image[0]) : ''"
                  fit="cover"
                  class="commodity-image"
                />
                <div class="commodity-detail">
                  <h3>{{ row.commodityName }}</h3>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="单价" width="120">
            <template #default="{ row }">
              <span class="price">¥{{ row.commodityPrice }}</span>
            </template>
          </el-table-column>
          
          <el-table-column label="数量" width="100" prop="quantity"></el-table-column>
          
          <el-table-column label="小计" width="120">
            <template #default="{ row }">
              <span class="subtotal">¥{{ row.subtotal }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 配送信息 -->
      <div class="section">
        <div class="section-title">配送信息</div>
        <div class="info-grid">
          <div class="info-item">
            <span class="label">配送状态：</span>
            <el-tag size="small">{{ deliveryStatusText }}</el-tag>
          </div>
          <div class="info-item">
            <span class="label">取件时间：</span>
            <span>{{ formatDate(orderDetail.delivery.pickupTime) || '暂无' }}</span>
          </div>
          <div class="info-item">
            <span class="label">预计送达：</span>
            <span>{{ formatDate(orderDetail.delivery.estimatedDeliveryTime) || '暂无' }}</span>
          </div>
          <div class="info-item">
            <span class="label">实际送达：</span>
            <span>{{ formatDate(orderDetail.delivery.actualDeliveryTime) || '暂无' }}</span>
          </div>
          <div class="info-item">
            <span class="label">配送备注：</span>
            <span>{{ orderDetail.delivery.deliveryNote || '无' }}</span>
          </div>
        </div>
      </div>
      
      <!-- 支付信息 -->
      <div class="section">
        <div class="section-title">支付信息</div>
        <div class="info-grid">
          <div class="info-item">
            <span class="label">支付状态：</span>
            <el-tag size="small" :type="orderDetail.payment.paymentStatus === 'SUCCESS' ? 'success' : 'warning'">
              {{ orderDetail.payment.paymentStatus === 'SUCCESS' ? '已支付' : '待支付' }}
            </el-tag>
          </div>
          <div class="info-item">
            <span class="label">支付流水号：</span>
            <span>{{ orderDetail.payment.paymentNo || '暂无' }}</span>
          </div>
          <div class="info-item">
            <span class="label">支付平台：</span>
            <span>{{ orderDetail.payment.paymentPlatform || '暂无' }}</span>
          </div>
          <div class="info-item">
            <span class="label">支付时间：</span>
            <span>{{ formatDate(orderDetail.payment.paymentTime) || '暂无' }}</span>
          </div>
          <div class="info-item">
            <span class="label">支付金额：</span>
            <span class="price">¥{{ orderDetail.payment.paymentAmount || orderDetail.order.actualAmount }}</span>
          </div>
        </div>
      </div>
      
      <!-- 金额信息 -->
      <div class="section">
        <div class="section-title">金额信息</div>
        <div class="amount-section">
          <div class="amount-item">
            <span>商品总额：</span>
            <span class="price">¥{{ orderDetail.order.totalAmount }}</span>
          </div>
          <div class="amount-item">
            <span>运费：</span>
            <span class="price">¥0.00</span>
          </div>
          <div class="amount-item total">
            <span>实付金额：</span>
            <span class="price">¥{{ orderDetail.order.actualAmount }}</span>
          </div>
        </div>
      </div>
      
      <!-- 操作区域 -->
      <div class="section">
        <div class="section-title">订单操作</div>
        <!-- 待支付状态显示支付表单和取消订单按钮 -->
        <div v-if="orderDetail.order.status === 'PENDING_PAYMENT'" class="action-section">
          <div class="payment-form" v-if="orderDetail.order.paymentType === 'ONLINE'">
            <h4>支付信息</h4>
            <el-form label-width="100px" :model="paymentInfo">
              <el-form-item label="支付流水号">
                <el-input v-model="paymentInfo.paymentNo" placeholder="请输入支付流水号"></el-input>
              </el-form-item>
              <el-form-item label="支付平台">
                <el-radio-group v-model="paymentInfo.paymentPlatform">
                  <el-radio label="ALIPAY">支付宝</el-radio>
                  <el-radio label="WECHAT">微信</el-radio>
                  <el-radio label="OTHER">其他</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" :loading="actionLoading.pay" @click="payOrder">
                  确认支付
                </el-button>
                <el-button type="danger" :loading="actionLoading.cancel" @click="cancelOrder">
                  取消订单
                </el-button>
              </el-form-item>
            </el-form>
          </div>
          <div class="cash-payment" v-else>
            <p>您选择了货到付款方式，商品将尽快安排发货。</p>
            <el-button type="danger" :loading="actionLoading.cancel" @click="cancelOrder">
              取消订单
            </el-button>
          </div>
        </div>
        
        <!-- 已支付状态 -->
        <div v-else-if="orderDetail.order.status === 'PAID'" class="action-section">
          <p>订单已支付，等待商家发货...</p>
        </div>
        
        <!-- 已发货状态显示确认收货按钮 -->
        <div v-else-if="orderDetail.order.status === 'SHIPPED'" class="action-section">
          <p>商品已发出，请注意查收。</p>
          <el-button type="primary" :loading="actionLoading.complete" @click="completeOrder">
            确认收货
          </el-button>
        </div>
        
        <!-- 已完成状态 -->
        <div v-else-if="orderDetail.order.status === 'COMPLETED'" class="action-section">
          <p>订单已完成，感谢您的购买！</p>
          <!-- 这里可以添加评价骑手的功能 -->
        </div>
        
        <!-- 已取消状态 -->
        <div v-else-if="orderDetail.order.status === 'CANCELLED'" class="action-section">
          <p>订单已取消。</p>
        </div>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.order-detail-container {
  margin: 20px auto;
  width: 95%;
  max-width: 1200px;
}

.order-detail-card {
  margin-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 15px;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-left h2 {
  margin: 0;
  margin-right: 10px;
  font-size: 20px;
  color: #333;
}

.section {
  margin-bottom: 30px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
  border-left: 3px solid #409EFF;
  padding-left: 10px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.info-item {
  display: flex;
}

.label {
  color: #909399;
  width: 100px;
}

.price, .subtotal {
  color: #f56c6c;
  font-weight: bold;
}

.address-info {
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f8f8f8;
}

.receiver-info {
  margin-bottom: 5px;
}

.name {
  font-weight: bold;
  margin-right: 15px;
}

.phone {
  color: #666;
}

.address {
  color: #333;
}

.commodity-info {
  display: flex;
  align-items: center;
}

.commodity-image {
  width: 60px;
  height: 60px;
  border-radius: 3px;
  margin-right: 10px;
}

.commodity-detail h3 {
  margin: 0;
  font-size: 14px;
}

/* 金额信息样式 */
.amount-section {
  background-color: #f8f8f8;
  padding: 15px;
  border-radius: 4px;
}

.amount-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.amount-item.total {
  font-weight: bold;
  font-size: 16px;
}

/* 操作区域样式 */
.action-section {
  background-color: #f8f8f8;
  padding: 15px;
  border-radius: 4px;
}

.payment-form h4 {
  margin-top: 0;
  margin-bottom: 15px;
}

.cash-payment p {
  margin-bottom: 15px;
}
</style> 